<template>
  <a-modal
    :title="passObj.id ? '编辑学生' : '新增学生'"
    :visible="props.isOpen"
    @ok="onSubmit"
    @cancel="handleCancel"
  >
    <a-form ref="formRef" :model="passObj">
      <a-form-item
        :rules="[
          { required: true, message: '请填写班级' },
          { max: 7, message: '班级最多输入7个字符' },
        ]"
        label="班级"
        name="class"
      >
        <a-input v-model:value="passObj.class" />
      </a-form-item>
      <a-form-item
        :rules="[
          { required: true, message: '请填写姓名' },
          { max: 5, message: '姓名最多输入7个字符' },
        ]"
        label="姓名"
        name="name"
      >
        <a-input v-model:value="passObj.name" />
      </a-form-item>
      <a-form-item
        :rules="[
          { required: true, message: '请填写学号' },
          { len: 9, message: '学号只能输入9个字符' },
        ]"
        label="学号"
        name="number"
      >
        <a-input v-model:value="passObj.number" />
      </a-form-item>
      <a-form-item
        :rules="[
          { required: true, message: '请填写学号' },
          { len: 1, message: '性别只能输入1个字符' },
        ]"
        label="性别"
        name="gender"
      >
        <a-input v-model:value="passObj.gender" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { message } from "ant-design-vue";
import { defineProps, defineEmits, ref, watchEffect } from "vue";
import { createStudent, updateStudent } from "../../../service/student";
// 编辑： 1. 点击编辑按钮， 2. 打开模态框  3. 填充当前这一条的数据
const props = defineProps({
  isOpen: {
    type: Boolean,
    required: true,
  },
  editData: {
    type: Object,
    required: false,
  },
});
const emit = defineEmits(["cancel", "success"]);
const passObj = ref({});
const formRef = ref(null);
// 1. 点击按钮  2. 触发表单验证  3， 通过表单验证后将数据传给后端 4. 提示用户成功 5. 关闭模态框 6. 刷新列表
const onSubmit = async () => {
  await formRef.value.validate();
  if (passObj.value.id) {
    // 有id就是编辑
    await updateStudent(passObj.value);
    message.success("编辑成功");
  } else {
    // 没有id就是新增
    await createStudent(passObj.value);
    message.success("新增成功");
  }
  emit("success");
};
watchEffect(() => {
  passObj.value = { ...props.editData };
});
// 1. 让父组件来关闭弹窗 2. 清除当前表单验证
const handleCancel = () => {
  emit("cancel");
  formRef.value.resetFields();
};
</script>

<style></style>
